/* eslint-disable array-callback-return */
/* eslint-disable guard-for-in */
/* eslint-disable react-hooks/exhaustive-deps */
/* eslint-disable react-hooks/rules-of-hooks */
import { doFetch } from '@/utils/doFetch';
import { ProTable } from '@ant-design/pro-components';
import { Tooltip } from 'antd';
import { memo, useEffect, useRef, useState } from 'react';
import LightFilters from './LightFilters';
import Resizecell from './Resizecell';

let handlEmptyChild = (tree = []) => {
  const newtree = tree.map((item) => {
    if (!item.children || item.children.length === 0) {
      item.value = item.key;
      return item;
    } else {
      item.value = item.key;
      return {
        ...item,
        children: handlEmptyChild(item.children),
      };
    }
  });
  return newtree;
};

const Mtable = (props) => {
  const {
    actionRef, //表格动作
    formRef, //表单Ref
    rowKey, // key
    columns = [], //columns
    style, //style
    path, //接口地址
    extraparams = {}, //额外参数
    pageSize, //修改默认pageSize
    pagination = true, //分页设置
    x, //横向滚动
    y,
    refreshDep, //依赖刷新 （已废弃）
    getDefaultSelected, //存在默认选中向上返回选中值
    resizeable = true,
    dataSource,
    iscurrent = true,
  } = props;

  const actionRefs = actionRef ?? useRef(),
    formRefs = formRef ?? useRef(),
    ifspagination = pagination === 'false' || pagination === false,
    [size, setsize] = useState(localStorage.getItem('SIZE') ?? 'small');

  const [columnes, setcolumnes] = useState(columns ?? []);

  //调用接口
  const request = async (params) => {
    if (dataSource) return dataSource;

    let newparams = {
      ...params,
      pageIndex: params.current,
      pageSize: params.pageSize || pageSize,
    };

    delete newparams.current;
    if (ifspagination) {
      delete newparams.pageIndex;
      delete newparams.pageSize;
    }

    const result = await doFetch({ url: path, params: newparams });
    //分页结果
    let data = result?.data?.page?.records,
      success = true,
      total = result?.data?.page?.total;
    //不带分页获取结果
    if (ifspagination) {
      data = result?.data?.dataList;
      total = result?.data?.dataList?.length;
    }
    //存在默认选中向上返回选中值
    getDefaultSelected && getDefaultSelected(result?.data);
    return {
      data,
      success,
      total,
    };
  };

  //更新 columns
  useEffect(() => {
    setcolumnes(() => {
      return columns.map((it, index) => {
        let options = {};
        if (!it.render) {
          options = {
            render: (text, row) => {
              return (
                <Tooltip title={row[it.dataIndex]} placement="topLeft">
                  <span className="table-cell">{row[it.dataIndex] ?? '-'}</span>
                </Tooltip>
              );
            },
          };
        }
        return {
          ...it,
          ...options,
          key: it.searchKey ?? it?.key,
          onHeaderCell: (column) => ({
            width: column.width,
            onResize: handleResize(index),
          }),
          valueType: it.searchValueType ?? it?.valueType,
        };
      });
    });
  }, [columns]);

  // 缩放表格
  const handleResize =
    (index) =>
    (e, { size }) => {
      setcolumnes((s) => {
        const nextColumns = [...s];
        nextColumns[index] = {
          ...nextColumns[index],
          width: size.width,
        };
        return nextColumns;
      });
    };

  // render表格拖拽
  const components = resizeable
    ? {
        components: {
          header: {
            cell: Resizecell,
          },
        },
      }
    : {};

  const [formval, setFormval] = useState({ });

  //获取默认值
  useEffect(() => {
    if (formRefs?.current) {
      setTimeout(() => {
        const initialFormValue = formRefs?.current?.getFieldsValue();
        setFormval((s) => ({
          ...s,
          ...initialFormValue,
        }));
      }, 10);
    }
  }, [formRefs]);

  //首次调用
  useEffect(() => {
    if (actionRefs?.current) {
      setTimeout(() => {
        actionRefs?.current?.reload();
      }, 100);
    }
  }, [columns, path, refreshDep, iscurrent, actionRefs]);

  return (
    <ProTable
      {...props}
      {...components}
      request={request}
      params={{...extraparams, ...formval}}
      searchFormRender={(props) => {
        const { columns } = props;
        return (
          <LightFilters
            formRef={formRefs}
            fields={columns ?? []}
            onValuesChange={(val, allval) => {
              setFormval(allval);
            }}
          />
        );
      }}
      size={size}
      onSizeChange={(size) => {
        localStorage.setItem('SIZE', size); //设置全局表格规格缓存
        setsize(size);
      }}
      columns={
        columnes?.filter?.(
          (it) => ['split', 'nosubmit'].indexOf(it.valueType) === -1,
        ) ?? []
      }
      style={style || {}}
      actionRef={actionRefs}
      rowKey={rowKey ?? 'id'} //表格每行数据的key
      dateFormatter="string"
      scroll={
        x || y
          ? {
              x: x,
              y: y,
            }
          : {}
      }
      pagination={
        pagination
          ? {
              showTotal: (total) => <span>共{total}条</span>,
              showQuickJumper: true,
              showSizeChanger: true,
              pageSizeOptions: [5, 10, 15, 30, 50, 100, 200],
              defaultPageSize: pageSize || 15,
            }
          : false
      }
      search={{
        filterType: 'light', //轻量模式
        placement: 'bottomLeft',
      }}
    />
  );
};

export default memo(Mtable);
